// pages/shopCart/shopCart.js
let http = require('../../utils/request.js');
let path = getApp().globalData.path
const filter = require('../../utils/filter.js');
Page(filter.loginCheck({

  /**
   * 页面的初始数据
   */
  data: {
    name: '购物车',
    checked: false,
    allChecked: false,
    edit: true,
    shopChoose: false,
    list: [],
    result: [],
    num: 1,
    minusStatus: 'disable',
    tmp: [],
    sumPrice: 0.00,
    baseurl: path,
    page:0,
    limit:5,
    isok:false,
    idarr:[]
  },
  // 单选方法
  changeCheckbox(event) {
    this.setData({
      idarr:event.detail
    })
    let chooseArr = event.detail
    this.setData({
      result: event.detail
    });
    let _this = this
    let tmp = _this.data.tmp

    let sumPrice = 0; //合计初始为0,
    tmp.forEach(val => {
      //将整个购物车列表循环
      if (_this.data.result.includes(val.id.toString())) {
        //val.id在result数组里，则为选中状态
        sumPrice += Number(val.price) * Number(val.goods_num)
      }
    })

    this.setData({
      sumPrice: sumPrice.toFixed(2),
      chooseArr
    })
    // console.log(Number(sumPrice), 'sumPrice')

  },
  // 全选方法
  chooseAllCheckbox(event) {
    this.setData({
      idarr:event.detail
    })
    let chooseArr = event.detail
    let tmpAll = this.data.tmp.map(val => {
      return val.id.toString();
    })
    if (this.data.allChecked) {
      this.setData({
        result: [],
        allChecked: false
      })
    } else {
      this.setData({
        result: tmpAll,
        allChecked: true

      })
    }
    this.setData({
      allChecked: this.data.result,
      chooseArr: this.data.result
    });
    let _this = this
    let tmp = _this.data.tmp
    // console.log(tmp,'tmp')
    let sumPrice = 0; //合计初始为0,
    tmp.forEach(val => {
      //将整个购物车列表循环
      if (_this.data.result.includes(val.id.toString())) {
        //val.id在result数组里，则为选中状态
        sumPrice += Number(val.price) * Number(val.goods_num)
      }
    })
    this.setData({
      sumPrice: sumPrice.toFixed(2),
    })
  },
  // 进步器
  changeStep(event) {
    // console.log(event.detail);
    let _this = this
    let step_goods_num = event.detail
    this.setData({
      goods_num,
      cartId
    })

  },
  // 编辑
  changeEdit(e) {
    let edit = this.data.edit
    if (edit == true) {
      this.setData({
        edit: false
      })
    } else {
      this.setData({
        edit: true
      })
    }
  },
  // 删除
  delectCart(e) {
    let _this = this
    let chooseArr = _this.data.chooseArr
    http.postHttp('/user_cart_del', {
      cart_id: chooseArr
    }, {}).then(res => {
      this.publik()
      if(_this.data.idarr.length!=0 || _this.data.idarr){
        if (this.data.allChecked) {
          this.setData({
            result: [],
            allChecked: false,
            tmp:[]
          })
        }else{
          for(let i=0;i<=_this.data.tmp.length;i++){
            for(let j=0;j<=_this.data.idarr.length;j++){
              if(_this.data.tmp[i].id == _this.data.idarr[j]){
                  _this.data.tmp.splice(i,1)
                  this.setData({
                    result: []
                  })
              }
            }
        }
        }
        
      }
     
    })
  },
  // 结算
  settlement(e) {
    let _this = this
    wx.setStorageSync('buyType', 2) //购物车购买
    let result = _this.data.result
    // console.log(_this.data.result,'result')
    if (result == '' || result == undefined) {
      wx.showToast({
        title: '请先选择商品',
        icon: 'none'
      })
    } else {
      wx.navigateTo({
        url: `/pages/confirmOrder/confirmOrder?result=${_this.data.result}&sumPrice=${_this.data.sumPrice}&isIntegral=0`,
      })
    }

  },

  // 进步器+-
  /*点击减号*/
  bindMinus: function (e) {
    let _this = this
    // var num = this.data.num;
    // if(num>1){
    //   num--
    // }


    let cartidUp = e.currentTarget.dataset.cartid
    let tmp = _this.data.tmp
    tmp.map((val, index) => {
      let goods_num = 'tmp[' + index + '].goods_num'
      var minusStatus = goods_num > 1 ? 'normal' : 'disable';
      if (val.id === cartidUp) {
        val.goods_num--
        this.setData({
          [goods_num]: val.goods_num
        })
        console.log(tmp[index].goods_num, '修改后数量')
        http.postHttp('/user_cart_add', {
          goods_num: tmp[index].goods_num,
          type: 3,
          cart_id: cartidUp
        }, {}).then(res => {
        })
      }

      this.setData({
        minusStatus: minusStatus
      })
    })
  },
  /*点击加号*/
  bindPlus: function (e) {
    let _this = this
    console.log(e.currentTarget.dataset.cartid, 'cartid+')
    var num = this.data.num;
    num++;
    var minusStatus = num > 1 ? 'normal' : 'disable';

    let cartidUp = e.currentTarget.dataset.cartid
    let tmp = _this.data.tmp
    tmp.map((val, index) => {
      let goods_num = 'tmp[' + index + '].goods_num'

      if (val.id === cartidUp) {
        val.goods_num++
        this.setData({
          [goods_num]: val.goods_num
        })
        console.log(tmp[index].goods_num, '修改后数量')
        http.postHttp('/user_cart_add', {
          goods_num: tmp[index].goods_num,
          type: 3,
          cart_id: cartidUp
        }, {}).then(res => {
        })
      }
    })
    this.setData({
      num: num,
      minusStatus: minusStatus
    })
  },


  publik(){
    this.setData({
      page:this.data.page+1
    })
    wx.showLoading({
      title: '加载中',
    })
    http.getHttp('/user_cart', {
      page: this.data.page,
      limit: this.data.limit,
    }, {
      token: wx.getStorageSync('token')
    }).then(res => {
      // wx.hideLoading()
      let tmpArr = res.data.data
      this.setData({
        tmp:this.data.tmp.concat(tmpArr)
      })
    })
  },

  /*输入框事件*/
  bindManual: function (e) {
    var num = e.detail.value;
    var minusStatus = num > 1 ? 'normal' : 'disable';
    this.setData({
      num: num,
      minusStatus: minusStatus
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // http.getHttp('/user_cart', {
    //   page: 1,
    //   limit: 10,
    // }, {
    //   token: wx.getStorageSync('token')
    // }).then(res => {
    //   let tmpArr = res.data.data
    //   this.setData({
    //     tmp: tmpArr
    //   })
    // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      isok:false,
      page:0,
      tmp:[]
    })
    this.publik()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.publik()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
}))